<?php namespace App\Services\Wechat;

use League\Flysystem\Exception;
use Requests;
use Requests_Exception;

class TulingRobot
{
    private $apiKey = 'a509322a6957436fbb2051b028ab863b';
    private $baseUrl = 'http://www.tuling123.com/openapi/api';

    public function sendInfo($userid,$content)
    {
        $result = self::doPost($this->baseUrl, [
            'key'    => $this->apiKey,
            'info'   => $content,
            'userid' => $userid,
        ]);
        return $result;
    }

    private function doPost($url, array $param)
    {
        $response = null;
        try {
            $response = Requests::post($url, [
                'Accept'       => 'text/plain;charset=utf-8',
                'Content-Type' => 'application/json;charset=utf-8',
            ],json_encode($param));
        } catch (Requests_Exception $ex) {
            throw new TulingException(TulingException::RequestsException, ['message' => $ex->getMessage()]);
        }

        $res = json_decode($response->body);
        if (is_null($res))
            throw new TulingException(TulingException::NotJson);

        return $res->text;
    }


}

class TulingException extends Exception
{
    const RequestsException = 0x01;
    const NotJson = 0x02;
    const OutOfService = 0x03;

    public function __construct($code, array $data = [], Exception $previous = null)
    {
        switch ($code) {
            case self::RequestsException:
                $message = trans('exception.tuling.requests_exception', []);
                break;
            case self::OutOfService:
            case self::NotJson:
                $message = trans('exception.tuling.out_of_service', []) . ' ' . $data['msg'];
                break;
            default:
                $message = trans('general.unknown_exception');
                break;
        }

        parent::__construct($message, $code, $previous);
    }
}